package com.bw.user.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SentinelConfig
 * @Author Hao_YunKai
 * @Date 2022/3/3 19:12
 */
@Configuration
public class SentinelConfig{
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    @PostConstruct
    private static void initRules() {
        //=============================规则1=========================
        FlowRule rule1 = new FlowRule();
        rule1.setResource("rule1");//规则名称
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);//如果设置0则按照线程数限流，如果设置1则按照QPS（每秒查询率）限流
        rule1.setCount(10);   // 每秒调用最大次数为 10 次
        rule1.setControlBehavior(2); //0快速失败，1预警，2排队等候
        rule1.setMaxQueueingTimeMs(1000);//排队超时阈值
        //还有其他规则可在官网查看
        //=============================规则2=========================
        FlowRule rule2 = new FlowRule();
        rule2.setResource("rule2");
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule2.setCount(2000);

        List<FlowRule> rules = new ArrayList<>();
        rules.add(rule1);
        rules.add(rule2);
        // 将控制规则载入到 Sentinel
        FlowRuleManager.loadRules(rules);
    }

}
